package com.reggie.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.UUID;
import com.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 文件上传于下载
 *
 * @author 78664
 */
@RestControllerAdvice
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Value("${reggie.pic-path}")
    private String basePath;

    /**
     * 文件上传
     *
     * @param file 本质是InputStreamSource
     * @return 成功与否
     */
    @PostMapping("/upload")
    public R<String> upload(@RequestPart("file") MultipartFile file) {
        log.info("开始文件上传，线程ID为：{}", Thread.currentThread().getId());
        log.info(file.toString());
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID() + suffix;
        File picDir = new File(basePath);
        if (!FileUtil.exist(picDir)) {
            picDir.mkdirs();
        }
        try {
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return R.success(fileName);
    }

    /**
     * 文件下载
     *
     * @param fileName        前端传来的文件名
     * @param servletResponse
     */
    @GetMapping("/download")
    public void download(@RequestParam("name") String fileName, HttpServletResponse servletResponse) {
        log.info("开始文件下载，线程ID为：{}", Thread.currentThread().getId());
        log.info(fileName.toString());
        servletResponse.setContentType("image/jpeg");
        // 输入流，读取文件内容
        // 输出流，给予浏览器文件
        try (
                FileInputStream fileInputStream = new FileInputStream(new File(basePath + fileName));
                ServletOutputStream outputStream = servletResponse.getOutputStream()
        ) {
            outputStream.write(IoUtil.readBytes(fileInputStream));
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
